<template>
  <div class="form-container" v-loading="loading">
    <el-form size="mini" ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item prop="title" label="详细描述">
        <el-input type="textarea" v-model="form.title" placeholder="请填写您要处置的物品名称、规格、新旧程度等，方便回收客户报价"></el-input>
      </el-form-item>
      <el-form-item prop="imgsList" label="图片视频">
        <el-upload :accept="accept" :limit="6" action="" list-type="picture-card" :on-preview="handlePictureCardPreview" :before-upload="beforeUpload1" :on-remove="handleRemove" :file-list="fileList" :http-request="handleUpload">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item prop="labels" label="标签">
        <div class="labels-list">
          <div @click="handleLabelsClick(item)" class="item" v-for="item in labels" :key="item" :class="{ active: form.labels.includes(item) }">
            {{ item }}
          </div>
        </div>
      </el-form-item>
      <el-form-item prop="address" label="所在地" @click.native="handleAddress">
        <el-input v-model="form.address" placeholder="请选择所在地"></el-input>
      </el-form-item>
      <el-form-item prop="priceSelect" label="预估价">
        <el-select @change="priceSelectChange" v-model="form.priceSelect" placeholder="请选择预估价">
          <el-option v-for="item in priceList" :key="item.key" :label="item.key" :value="item.key"></el-option>
        </el-select>
        <el-checkbox @change="priceCheckboxChange" style="margin-left: 20px" v-model="form.checkboxValue">面议</el-checkbox>
      </el-form-item>
      <el-form-item prop="user_name" label="联系人">
        <el-input v-model="form.user_name" placeholder="请填写发布人"></el-input>
      </el-form-item>
      <el-form-item prop="user_phone" label="联系电话">
        <el-input v-model="form.user_phone" placeholder="请填写手机号"></el-input>
      </el-form-item>
      <el-divider></el-divider>
      <el-form-item prop="power_sts" label="审核结果" v-if="mode === 'examine'">
        <el-radio-group v-model="form.power_sts">
          <el-radio :label="4">已通过</el-radio>
          <el-radio :label="3">未通过</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="push_type" label="推送渠道" v-if="form.power_sts === 4">
        <el-radio-group v-model="form.push_type">
          <el-radio :label="1">资产处置</el-radio>
          <el-radio :label="2">独享信息</el-radio>
          <el-radio :label="3">其他</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="refuse_reason_radio" label="未通过原因" v-if="form.power_sts === 3">
        <el-radio-group v-model="form.refuse_reason_radio">
          <el-radio label="未接通">未接通</el-radio>
          <el-radio label="已处理">已处理</el-radio>
          <el-radio label="其他">其他</el-radio>
        </el-radio-group>
        <el-input v-if="form.refuse_reason_radio === '其他'" v-model="form.refuse_reason_desc" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" @click="onCancel">取消</el-button>
        <el-button size="mini" type="primary" @click="onSubmit">确定</el-button>
      </el-form-item>
    </el-form>
    <!-- 图片预览 -->
    <el-dialog :visible.sync="dialogVisible" :modal="false">
      <div class="video-content">
        <video v-if="previewFile.name === 'video'" controls width="100%" height="500px">
          <source :src="previewFile.videoUrl" type="video/mp4" />
        </video>
        <img v-else :src="previewFile.url" alt="" />
      </div>
    </el-dialog>
    <!-- 选择地址 -->
    <el-dialog :visible.sync="dialogMapVisible" :modal="false">
      <aMap :location="this.form.location" @confirm="handleMapConfirm" @cancel="handleMapCancel"></aMap>
    </el-dialog>
  </div>
</template>
<script>
import aMap from './aMap.vue'
import { apiGetPostDetail, apiPostPower, apiUploadImg, apiPostEdit } from '@/api/wxapplet'
import { isMobile } from '@/utils/validate.js'

export default {
  props: {
    id: String,
    mode: String,
    labels: Array,
  },
  components: { aMap },
  data() {
    var validaMobile = (rule, value, callback) => {
      if (value && !isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      previewFile: '',
      dialogVisible: false,
      dialogMapVisible: false,
      priceList: [{ key: '5千以下' }, { key: '5千-1万' }, { key: '1万-5万' }, { key: '5万-10万' }, { key: '10万-15万' }, { key: '15万-50万' }, { key: '50万-100万' }, { key: '100万-200万' }, { key: '200万-500万' }, { key: '500万以上' }],
      form: {
        id: '',
        power_sts: '',
        push_type: '',
        refuse_reason: '',
        refuse_reason_radio: '',
        refuse_reason_desc: '',
        is_fast: 0,
        title: '',
        labels: '',
        address: '',
        price: '',
        pname: '',
        city_name: '',
        location: '',
        imgs: [],
        imgsList: [],
        user_name: '',
        user_phone: '',
        checkboxValue: false,
        priceSelect: '',
      },
      fileList: [],
      editForm: ['id', 'is_fast', 'title', 'labels', 'address', 'price', 'pname', 'city_name', 'location', 'imgs', 'user_name', 'user_phone'],
      examineForm: ['id', 'power_sts', 'push_type', 'refuse_reason', 'is_fast', 'title', 'labels', 'address', 'price', 'pname', 'city_name', 'location', 'imgs', 'user_name', 'user_phone'],
      rules: {
        title: [{ required: true, message: '请填写详情描述', trigger: 'blur' }],
        address: [{ required: true, message: '请选择所在地', trigger: 'blur' }],
        user_name: [{ required: true, message: '请填写联系人', trigger: 'blur' }],
        user_phone: [
          { required: true, message: '请填写联系电话', trigger: 'blur' },
          { validator: validaMobile, trigger: 'blur' },
        ],
        power_sts: [{ required: true, message: '请选择审核结果', trigger: 'blur' }],
        push_type: [{ required: true, message: '请选择推送渠道', trigger: 'blur' }],
        refuse_reason_radio: [{ required: true, message: '请选择未通过原因', trigger: 'blur' }],
      },
      // accept: 'image/jpeg,image/jpg,image/png',
      accept: 'image/jpeg,image/jpg,image/png, video/mp4',
      loading: false,
    }
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    // 获取详情
    getDetail() {
      const info = {
        id: this.id,
      }
      const formData = new FormData()
      for (let key in info) {
        formData.set(key, info[key])
      }
      apiGetPostDetail(formData).then((res) => {
        console.log(res)
        this.formData = res.data
        for (let key in this.form) {
          if (key in res.data) {
            this.form[key] = res.data[key]
          }
        }
        if (!this.form.labels) {
          this.form.labels = ''
        }
        this.form.pname = res.data.sheng
        this.form.city_name = res.data.shi
        this.form.power_sts = ''
        if (this.form.price === '面议') {
          this.form.checkboxValue = true
        } else {
          this.form.priceSelect = this.form.price
        }
        this.form.imgsList = JSON.parse(this.form.imgs)
        if (this.form.imgsList && this.form.imgsList.length > 0) {
          if (this.form.imgsList.length >= 6) {
            this.hideUpload()
          }
          this.form.imgsList = this.form.imgsList.map((item) => {
            const arr = item.split('.')
            const length = arr.length
            let name = item
            let url = item
            if (item.length > 0 && arr[length - 1].toLowerCase() === 'mp4') {
              url = 'http://recycleimg.feijiu.net/zft/mini/1702005217192.jpg'
              name = 'video'
              this.accept = 'image/jpeg,image/jpg,image/png'
            }
            return {
              videoUrl: item,
              name,
              url,
            }
          })
        }
        this.fileList = [...this.form.imgsList]
        this.addImageAttr()
      })
    },
    // 图片添加属性
    addImageAttr() {
      this.$nextTick(() => {
        const eleList = document.getElementsByClassName('el-upload-list__item-thumbnail')
        if (eleList && eleList.length > 0) {
          Array.prototype.forEach.call(eleList, (item) => {
            item.setAttribute('referrer', 'no-referrer|origin|unsafe-url')
            item.setAttribute('referrerPolicy', 'no-referrer')
          })
        }
      })
    },
    priceSelectChange() {
      this.form.checkboxValue = false
    },
    priceCheckboxChange() {
      this.form.priceSelect = ''
    },
    // 保存
    onSubmit() {
      this.$refs.form.validate((flag) => {
        if (flag) {
          this.form.imgs = this.form.imgsList.map((item) => {
            if (item.name === 'video') {
              return item.videoUrl
            } else {
              return item.url
            }
          })

          if (this.form.checkboxValue) {
            this.form.price = '面议'
          } else {
            this.form.price = this.form.priceSelect
          }

          this.loading = true

          if (this.mode === 'edit') {
            // 编辑
            const formData = new FormData()
            this.editForm.map((key) => {
              formData.set(key, this.form[key])
            })
            apiPostEdit(formData)
              .then((res) => {
                this.loading = false

                if (res.code !== 200) {
                  return
                }
                this.$message({
                  message: '操作成功！',
                  type: 'success',
                })
                setTimeout(() => {
                  this.$emit('refresh')
                }, 1000)
              })
              .catch(() => {
                this.loading = false
              })
          } else {
            this.form.power_sts = this.form.power_sts
            this.form.push_type = this.form.push_type
            if (this.form.refuse_reason_radio === '其他') {
              this.form.refuse_reason = this.form.refuse_reason_desc
            } else {
              this.form.refuse_reason = this.form.refuse_reason_radio
            }
            const formData = new FormData()
            this.examineForm.map((key) => {
              formData.set(key, this.form[key])
            })
            apiPostPower(formData)
              .then((res) => {
                this.loading = false

                if (res.code !== 200) {
                  return
                }
                this.$message({
                  message: '操作成功！',
                  type: 'success',
                })
                setTimeout(() => {
                  this.$emit('refresh')
                }, 1000)
              })
              .catch(() => {
                this.loading = false
              })
          }
        }
      })
    },
    // 取消
    onCancel() {
      this.$emit('close')
    },
    // 显示上传按钮
    showUpload() {
      const el = document.getElementsByClassName('el-upload el-upload--picture-card')[0]
      el.style.display = 'inline-block'
    },
    // 隐藏上传按钮
    hideUpload() {
      const el = document.getElementsByClassName('el-upload el-upload--picture-card')[0]
      el.style.display = 'none'
    },
    handleRemove(file, fileList) {
      console.log(file)
      if (file.name === 'video') {
        this.accept = 'image/jpeg, image/jpg, image/png, video/mp4'
      }
      this.form.imgsList = fileList
      this.showUpload()
    },
    handlePictureCardPreview(file) {
      this.previewFile = file
      this.dialogVisible = true
    },
    //   上传图片
    beforeUpload1(file) {
      const isLt2M = file.size / 1024 / 1024 < 20

      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 20MB!')
      }
      return isLt2M
    },
    handleUpload(file) {
      if (file.file.type.toLowerCase() === 'video/mp4') {
        this.accept = 'image/jpeg,image/jpg,image/png'
      }

      if (this.form.imgsList.length >= 5) {
        this.hideUpload()
      }
      const info = Object.assign({ file: file.file })
      const formData = new FormData()
      for (let key in info) {
        formData.set(key, info[key])
      }
      apiUploadImg(formData)
        .then((res) => {
          const url = res.data.url
          const arr = url.split('.')
          const length = arr.length
          if (url.length > 0 && arr[length - 1].toLowerCase() === 'mp4') {
            this.form.imgsList.push({
              url: 'http://recycleimg.feijiu.net/zft/mini/1702005217192.jpg',
              videoUrl: url,
              name: 'video',
            })
          } else {
            this.form.imgsList.push({
              url: url,
            })
          }
          this.addImageAttr()
        })
        .catch((e) => {})
    },
    // 打开地图
    handleAddress() {
      this.dialogMapVisible = true
    },
    // 选择地址
    handleMapConfirm(address) {
      this.dialogMapVisible = false
      console.log(address, 666)
      this.form.address = address.name
      const addressComponent = address.regeocode.addressComponent
      this.form.pname = addressComponent.province
      this.form.city_name = addressComponent.city || addressComponent.province
      this.form.location = `${address.lng}, ${address.lat}`
    },
    // 取消选择地址
    handleMapCancel() {
      this.dialogMapVisible = false
    },
    handleLabelsClick(label) {
      let arr = []
      if (this.form.labels) {
        arr = this.form.labels.split(',')
      }
      if (arr.includes(label)) {
        arr = arr.filter((item) => {
          return item != label
        })
      } else {
        arr.push(label)
      }
      this.form.labels = arr.join(',')
    },
  },
}
</script>
<style lang="scss">
.form-container {
  padding: 0 24px;
}

::v-deep .el-select {
  width: 100%;
}

.video-content {
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    max-height: 500px;
    max-width: 100%;
  }
}

.labels-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
  .item {
    cursor: pointer;
    &:hover {
      border: 1px solid #409eff;
      color: #409eff;
    }
    padding: 0 20px;
    height: 30px;
    border: 1px solid #999999;
    border-radius: 4px;
    margin-right: 10px;
    margin-bottom: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    &.active {
      border: 1px solid #409eff;
      background: #409eff;
      color: #ffffff;
    }
  }
}
</style>
